import shelve
import time
from flask import Flask,request,render_template,redirect,escape,Markup

application = Flask(__name__)
DATA_File="../data/guestbook.dat"

def save_data(name,comment,creat_at):
    """
    保存留言信息
    :param name:姓名
    :param comment: 评论内容
    :param creat_at: 创建时间
    :return:
    """

    database = shelve.open(DATA_File)
    if "greeting_list" not in database:
        greeting_list = []
    else:
        greeting_list = database["greeting_list"]

    greeting_list.insert(0,{
        'name':name,
        'comment':comment,
        'creat_at':creat_at,
    })

    database["greeting_list"] = greetin g_list

    database.close()

def load_data():
    """
    取数据
    :return:
    """
    database = shelve.open(DATA_File)

    greeting_list = database.get("greeting_list",[])

    database.close()
    return  greeting_list


#print()
#save_data('ocean','hello',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
#print(load_data())

@application.route('/')
def index():
    greetlist = load_data()
    return render_template('index.html',greetlist = greetlist)
@application.route("/post",methods=['POST'])
def post():
    name = request.form.get('name')
    comment = request.form.get('comments')
    creat_at = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    save_data(name,comment,creat_at)
    return redirect('/')

if __name__ == '__main__':
    application.run('127.0.0.1',5000,debug=True)
